import React from 'react';
import {withRouter, Redirect, Link} from 'react-router-dom';
import {inject, observer} from 'mobx-react';
import {Form, Icon, Input, Button, Checkbox} from 'antd';
import {loginApi} from '../api/auth';
import LoginBg from './Ui/LoginBg/LoginBg';
import '../css/pages/Login.css';

const FormItem = Form.Item;

@inject ('store')
@withRouter
@observer
class Login extends React.Component {
  state={
    isLoadingLogin: false
  }
  handleSubmit = e => {
    e.preventDefault ();
    const self = this;
    if(this.state.isLoadingLogin) {
      return ;
    }
    this.props.form.validateFields ((err, values) => {
      if (!err) {
        this.setState({
          isLoadingLogin: true
        });
        console.log ('Received values of form: ', values);
        loginApi (values).then (res => {
          console.log (res);
          if (res.token) {
            localStorage.setItem ('LINZ_BLOG_TOKEN', res.token);

            self.props.store.setLogin (true);
          }
        });
      }
    });
  };
  render () {
    const {login} = this.props.store.loginStatus;
    const {isLoadingLogin} = this.state;
    let from = {pathname: '/home'};
    const {getFieldDecorator} = this.props.form;
    if (this.props.location.state && this.props.location.state.from) {
      from = {pathname: this.props.location.state.from};
    }
    if (login) {
      return <Redirect to={from} />;
    }
    return (
      <div className="login-wrapper page-login">
        <Form onSubmit={this.handleSubmit} className="login-form">
          <h3>欢迎登录蒲公英投放系统</h3>
          <FormItem>
            {getFieldDecorator ('username', {
              rules: [{required: true, message: '请输入公司名称!'}],
            }) (
              <Input
                prefix={<Icon type="home" style={{color: 'rgba(0,0,0,.25)'}} />}
                placeholder="公司名称"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator ('password', {
              rules: [{required: true, message: '请输入密码!'}],
            }) (
              <Input
                prefix={<Icon type="lock" style={{color: 'rgba(0,0,0,.25)'}} />}
                type="password"
                placeholder="密码"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator ('remember', {
              valuePropName: 'checked',
              initialValue: true,
            }) (<Checkbox>记住密码</Checkbox>)}
            <Link className="login-form-forgot" to={{pathname: '/forget'}}>
              忘记密码？
            </Link>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
              loading={isLoadingLogin}
            >
              登录
            </Button>
            Or <Link to={{pathname: '/register'}}>马上注册</Link>
          </FormItem>
        </Form>
        <LoginBg />
      </div>
    );
  }
}

export default Form.create ({}) (Login);
